#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<malloc.h>
#define MAXQSIZE 101//最大队列长度  空一个存储空间解决假溢出
#define OK 1
#define ERROR -1

typedef struct
{
	int* base;
	int front;
	int rear;
}SqQueue;


void InitQueue(SqQueue* Q)
{
	Q->base = (int*)malloc(MAXQSIZE * sizeof(int));
	if (!Q->base)
		printf("存储分配失败!\n");
	else
		Q->front = Q->rear = 0;
}


void EntryQueue(SqQueue* Q)
{
	if (!Q->base)
		printf("该队列不存在!\n");
	else if ((Q->rear + 1) % MAXQSIZE == Q->front)
	{
		printf("队列已满,不能入队!\n");
	}	
	else
	{
		int e = 0;
		printf("请输入入队元素:");
		scanf("%d", &e);
		Q->base[Q->rear] = e;
		Q->rear = (Q->rear + 1) % MAXQSIZE;
	}
}

void OutQueue(SqQueue* Q)
{
	if (!Q->base)
		printf("该队列不存在!\n");
	else if (Q->rear == Q->front)
		printf("队列已空!\n");
	else
	{
		int e = 0;
		e = Q->base[Q->front];
		printf("出队元素为:%d\n", e);
		Q->front = (Q->front + 1) % MAXQSIZE;
	}
}


void IsEmpty(SqQueue* Q)
{
	if (!Q->base)
		printf("该队列不存在!\n");
	else if (Q->front == Q->rear)
		printf("队列为空!\n");
	else
		printf("队列不为空!\n");
}

void IsFull(SqQueue* Q)
{
	if (!Q->base)
		printf("该队列不存在!\n");
	else if ((Q->rear + 1) % MAXQSIZE == Q->front)
		printf("该队列已满!\n");
	else
		printf("该队列未满!\n");
}

void GetFront(SqQueue* Q)
{
	if (!Q->base)
		printf("该队列不存在!\n");
	else if (Q->front == Q->rear)
		printf("队列为空!\n");
	else
	{
		int e = 0;
		e = Q->base[Q->front];
		printf("队头元素为:%d\n", e);
	}
}

void LengthQueue(SqQueue* Q)
{
	if (!Q->base)
		printf("该队列不存在!\n");
	else
	{
		int i = (Q->rear - Q->front + MAXQSIZE) % MAXQSIZE;
		if (i == 0)
			printf("该队列为空,队列长度为:%d\n", i);
		else
			printf("队列长度为:%d\n", i);
	}
}


void TraverseQueue(SqQueue* Q)
{
	if (!Q->base)
		printf("该队列不存在!\n");
	else 
	{
		int head = Q->front;
		while (1)
		{
			if (head % MAXQSIZE == Q->rear)
				break;
			else
			{
				printf("%d ", Q->base[head]);
				head = (head + 1) % MAXQSIZE;
			}
		}
		printf("\n");
	}	
}



int main()
{
	SqQueue Q = { Q.base = NULL };
	printf("    顺序队列    \n");
	printf("0.退出操作.\n");
	printf("1.初始化队列.\n");
	printf("2.入队.\n");
	printf("3.出队.\n");
	printf("4.判断是否为空.\n");
	printf("5.判断队列是否满.\n");
	printf("6.获取队头元素.\n");
	printf("7.获取队列长度.\n");
	printf("8.遍历队列.\n");
	while (1)
	{
		int x = 0;
		int n = 0;
		printf("请选择你的操作:");
		scanf("%d", &n);
		switch (n)
		{
		case 0:
			x = 1;
			break;
		case 1:
			InitQueue(&Q);
			break;
		case 2:
			EntryQueue(&Q);
			break;
		case 3:
			OutQueue(&Q);
			break;
		case 4:
			IsEmpty(&Q);
			break;
		case 5:
			IsFull(&Q);
			break;
		case 6:
			GetFront(&Q);
			break;
		case 7:
			LengthQueue(&Q);
			break;
		case 8:
			TraverseQueue(&Q);
			break;
		}
		if (x == 1)
			break;
	}
	return 0;
}